package ntriples

import "rdf"
import "bufio"
import "os"
import "strings"
import "unicode"
import "regexp"

var pattern = regexp.MustCompile( "(\"[^\"]\")?[^ ]+" )

func ReadWith( filename string, consumer func (*rdf.Triple) ) {
  a, _ := os.Open( filename, 0, 0 )
  b := bufio.NewReader( a )
  prefixes := make(map[string]string)
  for {
    s, err := b.ReadString( '\n' )
    if err != nil { break }
    s = s[0:len(s)-1]
    items := pattern.AllMatchesString( s, 0 )
    if len(s) == 0 {
      // nothing to do
    } else if items[0] == "@prefix" {
      prefixes[items[1]] = items[2]
    } else {
        t := rdf.NewTriple( node(prefixes, items[0]), node(prefixes,items[1]), node(prefixes,items[2]) )
        consumer( t )
    }
  }
}

func node( prefixes map[string]string, spelling string ) *rdf.Node {
  if unicode.IsLetter(int(spelling[0]))  {
    cp := strings.Index( spelling, ":" )
    prefix := spelling[0:cp+1]
    uri, present := prefixes[prefix]
    if present { spelling = uri[0:len(uri)-1] + spelling[cp+1:] + ">" }
  }
  return rdf.NewNode( spelling )
}
